// apiService.ts
export default class ApiService {
  baseUrl: string;
  token: string; // 新增token属性

  constructor(baseUrl: string, token: string) {
    // 修改构造函数以接收token
    this.baseUrl = baseUrl;
    this.token = token; // 保存token
  }

  async get(url: string): Promise<any> {
    try {
      const response = await fetch(`${this.baseUrl}${url}`, {
        headers: this.getHeaders(), // 使用getHeaders方法添加headers
      });
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return await response.json();
    } catch (error) {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      throw error;
    }
  }

  async post(url: string, data: any): Promise<any> {
    try {
      data = { ...data };
      if (this.token) data.token = this.token; // 添加token到请求数据中

      const response = await fetch(`${this.baseUrl}${url}`, {
        method: "POST",
        headers: this.getHeaders(), // 使用getHeaders方法添加headers
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return await response.json();
    } catch (error) {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      throw error;
    }
  }

  async put(url: string, data: any): Promise<any> {
    try {
      data = { ...data };
      if (this.token) data.token = this.token; // 添加token到请求数据中
      if (data._id) data.行ID = data._id; // 添加行ID到请求数据中

      const response = await fetch(`${this.baseUrl}${url}`, {
        method: "PUT",
        headers: this.getHeaders(), // 使用getHeaders方法添加headers
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return await response.json();
    } catch (error) {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      throw error;
    }
  }

  async delete(url: string, data: any): Promise<any> {
    try {
      data = { ...data };
      if (this.token) data.token = this.token; // 添加token到请求数据中
      if (data._id) data.行ID = data._id; // 添加行ID到请求数据中

      const response = await fetch(`${this.baseUrl}${url}`, {
        method: "DELETE",
        headers: this.getHeaders(), // 使用getHeaders方法添加headers
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        throw new Error("Network response was not ok");
      }
      return await response.json();
    } catch (error) {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
      throw error;
    }
  }

  // 新增方法，用于获取请求头
  private getHeaders(): Headers {
    const headers = new Headers();
    headers.append("Content-Type", "application/json");
    headers.append("Authorization", `${this.token}`); // 添加token到Authorization头
    return headers;
  }
}
